
import time
import json

from utils.db_base import MyDB

db = MyDB()
#  检测token有效性
def check_token(token):
    user = None
    expired_at = int(time.time())
    query = f'select * from token where token=\'{token}\' and expired_at > {expired_at}'
    result = db.find_first(query)
    if result:
        # 获取用户信息
        user = {
            'user_id'    : result['user_id'],
            'token_type' : result['token_type'],
            'expired_at':result['expired_at']
        }
        # 获取用户权限
        query = f'select * from user where user_id={result["user_id"]}'
        result = db.find_first(query)
        user['level_id'] = result['level_id']
    return user

def insert_visit(user_id,name):    
    sql = f'insert into application_visit(name,user_id,times,date) values(\'{name}\',{user_id},1,\'{time.strftime("%Y-%m-%d", time.localtime())}\')'
    print(sql)
    return db.insertOrUpdate(sql)

def update_visit(user_id,name):
    sql = f'update application_visit set times=times+1 where user_id={user_id} and name=\'{name}\' and date=\'{time.strftime("%Y-%m-%d", time.localtime())}\''
    return db.insertOrUpdate(sql)


def get_today_visit(name,user_id):
     # 没有兑换码 访问受限制 查看是否超限制
        sql = f'select * from application_visit where user_id={user_id} and name=\'{name}\' and date=\'{time.strftime("%Y-%m-%d", time.localtime())}\''
        print(sql)
        return db.find_first(sql)
def set_today_visit(user_id,name ):
    res = get_today_visit(name,user_id)
    return update_visit(user_id,name) if res else insert_visit(user_id,name)    
def verify_visit(user_id,level_id,name):   
    # 用户等级是1 新用户无限制  2 限制 3 看兑换码是否过期 过期就限制 不过期就不限制
    # db = MyDB()
    def today_visit_verify_limit():
        # 查看今日访问次数
        res = get_today_visit(name,user_id)
        times = 0
        if res:            
            times = res['times']
        # 查看访问限制
        sql = f'select * from application_config where config_name="visit_limits"'
        res = db.find_first(sql)
        if res:
            val = json.loads(res['config_items'])
            print(val)
            print(val['value'])
            return  times >= val['value'][name]
        return False
    #不受限制 
    is_limit = False 
    if level_id==3:
        # 存在没有过期的兑换码
        expired_at = int(time.time())
        sql = f'select * from redemption_code where user_id={user_id} and expired_at>={expired_at}'
        code = db.find_first(sql)
        if code==None:
            # 不存在没有过期的兑换码
            # 更新用户等级
            sql = f'update user set level_id=2 where user_id={user_id}'
            db.insertOrUpdate(sql)
            is_limit = today_visit_verify_limit()
    else :
        if level_id==2:
            is_limit = today_visit_verify_limit()       
   
    return is_limit
 # 关闭数据库连接